var express = require('express');
var router = express.Router();
var uuid = require('uuid').v1;


router.get('/function', async function (req, res, next) {
    var projectId = req.query.projectId;
    var Sql = `SELECT * FROM project_function WHERE project_id = ? AND disable = 0`;
    try {
        var vals = await asyncQuery(Sql, [projectId]);
        res.json(vals);
    } catch (error) {
        next(error)
    };
});

router.post('/function', async function (req, res, next) {
    var functionId = uuid();

    var data = {
        function_id: functionId,
        project_id: req.body.projectId,
        test: req.body.test,
        code: req.body.code,
        key: req.body.key,
        name: req.body.name,
        disable: 0,
    };

    var Sql = `INSERT INTO project_function SET ?`;
    try {
        await Permission.CPP(req.headers.token,  req.query.projectId);
        await asyncQuery(Sql, data);
        res.json({
            id: functionId
        });
    } catch (error) {
        next(error)
    };
})


router.put('/function', async function (req, res, next) {
    var functionId = req.body.functionId;
    var data = {
        test: req.body.test,
        code: req.body.code,
        key: req.body.key,
        name: req.body.name,
    };

    var Sql = `UPDATE project_function SET ? WHERE function_id = ?`;
    try {
        await Permission.CPP(req.headers.token,  req.query.projectId);
        await asyncQuery(Sql, [data, functionId]);
        res.json({});
    } catch (error) {
        next(error)
    };
});


router.delete('/function', async function (req, res, next) {
    var functionId = req.body.functionId;
    var Sql = `UPDATE project_function SET  disable = 1 WHERE function_id = ?`;
    try {
        await Permission.CPP(req.headers.token,  req.query.projectId);
        await asyncQuery(Sql, [functionId]);
        res.json({});
    } catch (error) {
        next(error)
    };
});


module.exports = router;